package com.easychat.websocket.netty;

import com.easychat.entity.dto.MessageSendDto;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Author Dongdong
 * @注释 消息处理器
 */
@Component("messageHandler")
public class MessageHandler {
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private ChannelContextUtils channelContextUtils;
    //通道
    private static final String MESSAGE_TOPIC = "message.topic";

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(MessageHandler.class);

    //订阅频道
    @PostConstruct
    //在项目启动的时候执行
    public void listenMessage() {
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        //监听消息
        rTopic.addListener(MessageSendDto.class, (MessageSendDto, sendDto) -> {
            logger.info("收到消息：{}", sendDto);
            //将消息发送给用户
            channelContextUtils.sendMessage(sendDto);
        });
    }

    public void sendMessage(MessageSendDto message) {
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.publish(message);
    }

}
